import { getHost } from "./host";

declare global {
    interface Window {
        config: Config;
        __AppFlag__: any;
    }
}

/** 标识 */
window.__AppFlag__ = {
    version: "1.0.0",
    run,
    setConfig,
    updateConfig,
};

console.log("运行脚本", "version", window.__AppFlag__.version);

/** 当前窗口 */
const scriptWV = plus.webview.getWebviewById("scriptWV");

// 清除自动跳转到配置页
const mainWV = plus.webview.getLaunchWebview();
mainWV.evalJS("clearTimeout(timeHandle);");

/** 配置 */
export interface Config {
    targetUrl: string;
    projectName: string;
    userName: string;
    password: string;
    host: string;
    dev: string;
}
//获取运行配置
let config: Config = JSON.parse(plus.storage.getItem("config") || "{}");
setHtml();

if (!config.targetUrl || !config.projectName || !config.userName || !config.password) {
    setConfig();
} else {
    run();
}

let errorCount = 0;
let maxErrorCount = 2;
function run() {
    if (!config.host) {
        getHost(config);
        return;
    }
    main().catch((e) => {
        console.error("运行出错", e);
        config.host = "";
        if (++errorCount >= maxErrorCount) {
            errorCount = 0;
            setConfig();
        } else {
            getHost(config);
        }
    });
}

async function main() {
    let href = config.host;
    let res = await fetch(href).then((v) => v.text());
    if (res.includes("<h1>404</h1>")) {
        return Promise.reject(404);
    } else if (res.includes("unavailable</h2>")) {
        mainWV.evalJS(`setLog("没有可用的路线或者服务未启动！");`);
        setConfig(2 * 1000);
        return;
    }

    let bodyWV = plus.webview.create(href, "body");
    bodyWV.addEventListener("loaded" as PlusWebviewWebviewEvent, () => {
        bodyWV.show("slide-in-right" as PlusWebviewAnimationTypeShow);
    });
}

/** 设置配置文件 */
function setConfig(time = 0) {
    setTimeout(() => {
        scriptWV.show("slide-in-right" as PlusWebviewAnimationTypeShow);
    }, time);
}

/** 更新配置文件 */
function updateConfig(conf: Config) {
    config = conf;
    plus.storage.setItem("config", JSON.stringify(config));
    console.log("[ config ]-96", JSON.stringify(config));
}

/** 添加页面页面html */
function setHtml() {
    document.body.innerHTML = `
    <style>
            body {
                height: 100vh;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
            }
            .form {
                padding-right: 30px;
            }
            .row {
                display: flex;
                padding-bottom: 15px;
            }
            .label {
                width: 70px;
                padding-right: 15px;
                text-align: right;
            }
            .btn {
                width: 170px;
            }
        </style>
        <div class="form">
            <div class="row">
                <div class="label">地址:</div>
                <input class="targetUrl" type="text" />
            </div>
            <div class="row">
                <div class="label">项目名:</div>
                <input class="projectName" type="text" />
            </div>
            <div class="row">
                <div class="label">账户:</div>
                <input class="userName" type="text" />
            </div>
            <div class="row">
                <div class="label">密码:</div>
                <input class="password" type="password" />
            </div>            
            <div class="row">
                <div class="label">DEV:</div>
                <input class="dev" type="text" />
            </div>
            <div class="row">
                <div class="label"></div>
                <button class="btn">确认</button>
            </div>
        </div>
    `;

    let targetUrl_Dom = document.querySelector<HTMLInputElement>(".targetUrl");
    let projectName_Dom = document.querySelector<HTMLInputElement>(".projectName");
    let userName_Dom = document.querySelector<HTMLInputElement>(".userName");
    let password_Dom = document.querySelector<HTMLInputElement>(".password");
    let dev_Dom = document.querySelector<HTMLInputElement>(".dev");
    let btnDom = document.querySelector<HTMLElement>(".btn");

    // 初始值
    targetUrl_Dom!.value = config.targetUrl || "";
    projectName_Dom!.value = config.projectName || "";
    userName_Dom!.value = config.userName || "";
    password_Dom!.value = config.password || "";
    dev_Dom!.value = config.dev || "";
    console.log("[ config ]-162", JSON.stringify(config));

    btnDom?.addEventListener("click", () => {
        config.targetUrl = targetUrl_Dom?.value.trim() || config.targetUrl;
        config.projectName = projectName_Dom?.value.trim() || config.projectName;
        config.userName = userName_Dom?.value.trim() || config.userName;
        config.password = password_Dom?.value.trim() || config.password;
        config.password = password_Dom?.value.trim() || config.password;
        config.dev = dev_Dom?.value.trim() || config.dev;
        console.log("[ config ]-170", JSON.stringify(config));
        if (config.dev) {
            config.host = config.dev;
        } else if (!config.targetUrl || !config.projectName || !config.userName || !config.password) {
            console.log("每一项不能为空");
            return;
        }

        updateConfig(config);
        run();
        scriptWV.hide("slide-out-right" as PlusWebviewAnimationTypeClose);
    });
}
